var express = require('express')
var router = express.Router()

const moment = require('moment')
const AccountModel = require('../../models/AccountModel')
const checkLoginMiddleware = require('../../middlewares/checkLoginMiddleware')

// 添加首页路由规则
router.get('/', (req, res) => {
  res.redirect('/account')
})

//记账本的列表
router.get('/account', checkLoginMiddleware, async function (req, res, next) {
  try {
    // 获取所有账单信息
    const accounts = await AccountModel.find().sort({ time: -1 }).exec()
    res.render('list', { accounts, moment })
  } catch (err) {
    res.status(500).send('读取失败')
  }
})

//添加记录
router.get('/account/create', checkLoginMiddleware, function (req, res, next) {
  res.render('create')
})

//新增记录
router.post('/account', checkLoginMiddleware, (req, res) => {
  // 插入数据库
  AccountModel.create({
    ...req.body,
    // 修改 time 属性的值
    time: moment(req.body.time).toDate(),
  })
    .then((data) => {
      // 成功提醒
      res.render('success', { msg: '添加成功哦~~~', url: '/account' })
    })
    .catch((err) => {
      res.status(500).send('插入失败~~')
    })
})

//删除记录
router.get('/account/:id', checkLoginMiddleware, async (req, res) => {
  try {
    const id = req.params.id
    const data = await AccountModel.deleteOne({ _id: id })

    if (data.deletedCount > 0) {
      res.render('success', { msg: '删除成功~~~', url: '/account' })
    } else {
      res.status(404).send('未找到匹配的文档，无法删除')
    }
  } catch (err) {
    res.status(500).send('删除失败~')
  }
})

module.exports = router
